<div class="widget-body ">
	<div class="">
		<h3>信息</h3>
		<table class="table no-border">

			<tbody>
				<tr>
					<th id="siteName">所属站点:</th>
					<th id="areaName">所属区域:</th>
					<th id="owner">所属用户:</th>
				</tr>
				<tr>
					<th id="businessSystemName">所属系统:</th>
					<th id="businessSubSystemName">所属子系统:</th>
					<th id="servName">服务名称:</th>
				</tr>
				<tr>
					<th id="statusText">服务状态:</th>
					<th id="createDateTime">创建时间:</th>
					<th id="taskStatusText">任务状态:</th>
				</tr>
			</tbody>
		</table>

	</div>
	<div class="row">
		<div id="list-alert"></div>
	</div>
	<ul id="myTab1" class="nav nav-tabs bordered">
		<li class="active"><a id="upsqlTab" onclick="upsqlTabClick()"
			href="#s1" data-toggle="tab">数据库模块</a></li>
		<li><a id="upproxyTab" onclick="upproxyTabClick()" href="#s1"
			data-toggle="tab">代理模块</a></li>
		<li><a id="swmTab" onclick="swmTabClick()" href="#s1"
			data-toggle="tab">高可用模块</a></li>
		<li><a id="upsqlParamTab" onclick="paramTabClick('upsql')"
			href="#s2" data-toggle="tab">数据库参数</a></li>
		<li><a id="upproxyParamTab" onclick="paramTabClick('upproxy')"
			href="#s2" data-toggle="tab">代理参数</a></li>
		<li><a id="databaseTab" onclick="databaseTabClick()" href="#s7"
			data-toggle="tab">数据库管理</a></li>
		<li><a id="userTab" onclick="userTabClick()" href="#s6"
			data-toggle="tab">用户管理</a></li>
		<li><a id="userTab" onclick="userDirectTabClick()" href="#s66"
			data-toggle="tab">直连用户</a></li>
		<li><a id="backupStrategyTab" href="#s4"
			onclick="backupStrategyTabClick()" data-toggle="tab">备份策略</a></li>
		<li><a id="backupListTab" href="#s3"
			onclick="backupListTabClick()" data-toggle="tab">备份列表</a></li>
		<li><a id="monitorTab" href="#s12" data-toggle="tab">监控指标</a></li>
		<li><a id="relationMonitorTab"
			onclick="relationMonitorTabClick()" href="#s5" data-toggle="tab">主从监控</a>
		</li>
	</ul>
	<div id="myTabContent1" class="tab-content">
		<div class="tab-pane fade in active " id="s1">
			<!-- Dynamic Modal -->
			<div class="modal fade" id="s1remoteModal" tabindex="-1"
				role="dialog" aria-labelledby="s1remoteModalLabel"
				aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<!-- content will be filled here from "ajax/modal-content/model-content-1.html" -->
					</div>
				</div>
			</div>
			<div class="modal fade" id="slowlogModal" tabindex="-1" role="dialog"
				aria-labelledby="slowlogModalLabel" aria-hidden="true">
				<div class="modal-dialog" style="width: 1400px;">
					<div class="modal-content">
						<!-- content will be filled here from "ajax/modal-content/model-content-1.html" -->
					</div>
				</div>
			</div>
			<br> <a href="javascript:void(0);" class="btn btn-success"
				onclick="unit('start')">启动</a> <a href="javascript:void(0);"
				class="btn btn-danger" onclick="unit('stop')">停止</a> <a
				href="javascript:void(0);" class="btn btn-primary"
				onclick="unit('backup')" id="backupBtn">备份</a> <a
				href="javascript:void(0);" class="btn btn-danger"
				onclick="unit('restore')" id="restoreBtn">还原</a> <a
				href="javascript:void(0);" class="btn btn-info"
				onclick="unit('migrate')">迁移</a> <a href="javascript:void(0);"
				class="btn btn-danger" onclick="unit('rebuild')" id="rebuildBtn">重建</a>
			<a href="javascript:void(0);" class="btn btn-primary"
				onclick="unit('monitor')" id="unitMonitor">监控</a> <a
				href="javascript:void(0);" class="btn btn-warning"
				onclick="unit('isolate')" id="isolateBtn">隔离</a> <a
				href="javascript:void(0);" class="btn btn-danger"
				onclick="unit('recover')" id="recoverBtn">回切</a> <a
				href="javascript:void(0);" class="btn btn-success"
				onclick="unit('slowlog')" id="slowlog">慢日志</a>
			<p>&nbsp;</p>
			<table id="jqgrid"></table>
			<div id="pjqgrid"></div>
		</div>
		<div class="tab-pane fade" id="s2">
			<div class="modal fade" id="s2remoteModal" tabindex="-1"
				role="dialog" aria-labelledby="s2remoteModalLabel"
				aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<!-- content will be filled here from "ajax/modal-content/model-content-1.html" -->
					</div>
				</div>
			</div>
			<br> <a href="javascript:void(0);" class="btn btn-info"
				onclick="editParam()" id="updateParam">编辑</a>
			<p>&nbsp;</p>
			<table id="jqgridParam"></table>
			<div id="pjqgridParam"></div>
		</div>
		<div class="tab-pane fade" id="s3">
			<div class="modal fade" id="s3remoteModal" tabindex="-1"
				role="dialog" aria-labelledby="s3remoteModalLabel"
				aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<!-- content will be filled here from "ajax/modal-content/model-content-1.html" -->
					</div>
				</div>
			</div>
			<br>
			<p>&nbsp;</p>
			<table id="jqgridBackupList"></table>
			<div id="pjqgridBackupList"></div>
		</div>
		<div class="tab-pane fade" id="s4">
			<div class="modal fade" id="s4remoteModal" tabindex="-1"
				role="dialog" aria-labelledby="s4remoteModalLabel"
				aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<!-- content will be filled here from "ajax/modal-content/model-content-1.html" -->
					</div>
				</div>
			</div>
			<br> <a href="javascript:void(0);" class="btn btn-success"
				onclick="addBackupStrategyClick()" id="addBackupStrategy">增加</a> <a
				href="javascript:void(0);" class="btn btn-info"
				onclick="backupStrategyClick('edit')" id="editBackupStrategy">编辑</a>
			<a href="javascript:void(0);" class="btn btn-danger"
				onclick="backupStrategyClick('delete')" id="deleteBackupStrategy">删除</a>
			<a href="javascript:void(0);" class="btn btn-primary"
				onclick="backupStrategyClick('start')" id="startBackupStrategy">启用</a>
			<a href="javascript:void(0);" class="btn btn-danger"
				onclick="backupStrategyClick('stop')" id="stopBackupStrategy">停用</a>
			<p>&nbsp;</p>
			<table id="jqgridBackupStrategy"></table>
			<div id="pjqgridBackupStrategy"></div>
		</div>
		<div class="tab-pane fade" id="s5">
			<div class="modal fade" id="s5remoteModal" tabindex="-1"
				role="dialog" aria-labelledby="s5remoteModalLabel"
				aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<!-- content will be filled here from "ajax/modal-content/model-content-1.html" -->
					</div>
				</div>
			</div>
			<br>
			<p>&nbsp;</p>
			<table id="jqgridRelation"></table>
			<div id="pjqgridRelation"></div>
		</div>
		<div class="tab-pane fade" id="s6">
			<div class="modal fade" id="s6remoteModal" tabindex="-1"
				role="dialog" aria-labelledby="s6remoteModalLabel"
				aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<!-- content will be filled here from "ajax/modal-content/model-content-1.html" -->
					</div>
				</div>
			</div>
			<br> <a href="javascript:void(0);" class="btn btn-success"
				onclick="userClick('add')" id="addUser">增加</a> <a
				href="javascript:void(0);" class="btn btn-danger"
				onclick="userClick('delete')" id="deleteUser">删除</a>
			<p>&nbsp;</p>
			<table id="jqgridUser"></table>
			<div id="pjqgridUser"></div>
		</div>
		<div class="tab-pane fade" id="s66">
			<div class="modal fade" id="s66remoteModal" tabindex="-1"
				role="dialog" aria-labelledby="s66remoteModalLabel"
				aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<!-- content will be filled here from "ajax/modal-content/model-content-1.html" -->
					</div>
				</div>
			</div>
			<br> <a href="javascript:void(0);" class="btn btn-success"
				onclick="userClick('addDirect')" id="addUserDirect">增加</a> <a
				href="javascript:void(0);" class="btn btn-danger"
				onclick="userClick('deleteDirect')" id="deleteUserDirect">删除</a>
			<p>&nbsp;</p>
			<table id="jqgridUser"></table>
			<div id="pjqgridUser"></div>
		</div>
		<div class="tab-pane fade" id="s7">
			<div class="modal fade" id="s7remoteModal" tabindex="-1"
				role="dialog" aria-labelledby="s7remoteModalLabel"
				aria-hidden="true">
				<div class="modal-dialog" style="margin-top: 10%; width: 300px;">
					<div class="modal-content">
						<!-- content will be filled here from "ajax/modal-content/model-content-1.html" -->
					</div>
				</div>
			</div>
			<br> <a href="javascript:void(0);" class="btn btn-success"
				onclick="databaseClick('add')" id="addDatabase">增加</a> <a
				href="javascript:void(0);" class="btn btn-danger"
				onclick="databaseClick('delete')" id="deleteDatabase">删除</a>
			<p>&nbsp;</p>
			<table id="jqgridDatabase"></table>
			<div id="pjqgridDatabase"></div>
		</div>
		<div class="tab-pane fade" id="s12">
			<div class="modal fade" id="s12remoteModal" tabindex="-1"
				role="dialog" aria-labelledby="s12remoteModalLabel"
				aria-hidden="true">
				<div class="modal-dialog">
					<div class="modal-content">
						<!-- content will be filled here from "ajax/modal-content/model-content-1.html" -->
					</div>
				</div>
			</div>
			<p>&nbsp;</p>
			<div class="row">
				<article class="col-sm-24 col-md-24 col-lg-12"
					style="padding-left: 13px; padding-right: 5px">
					<div class="jarviswidget" id="wid-id-0"
						data-widget-colorbutton="false" data-widget-editbutton="false"
						data-widget-togglebutton="false" data-widget-deletebutton="false"
						data-widget-fullscreenbutton="false"
						data-widget-custombutton="false" data-widget-sortable="false"
						style="height: 280px;">
						<header>
							<span class="widget-icon"> <i
								class="glyphicon glyphicon-stats txt-color-darken"></i></span>
							<h2>日资源使用监控</h2>
							<div class="col-sm-4 col-md-4 col-lg-2">
								<label class="select"> <select class="required"
									style="width: 150px" id="metricSelectDay"
									name="metricSelectDay">
										<option value="">选择监控项</option>
								</select>
								</label>
							</div>
							<div class="col-sm-6 col-md-6 col-lg-3 input-group">
								<input class="form-control" id="timepicker" type="text"
									placeholder="Select time"> <span
									class="input-group-addon"><i class="fa fa-clock-o"></i></span>
							</div>
						</header>
						<!-- widget div-->
						<!-- widget edit box -->
						<div class="jarviswidget-editbox"></div>
						<!-- end widget edit box -->
						<!-- content -->
						<div id="chartDay" class="chart txt-color-blue"
							style="height: 260px;"></div>
						<!-- end widget div -->
					</div>
				</article>
			</div>
			<div class="row">
				<article class="col-sm-24 col-md-24 col-lg-12"
					style="padding-left: 13px; padding-right: 5px">
					<div class="jarviswidget" id="wid-id-1"
						data-widget-colorbutton="false" data-widget-editbutton="false"
						data-widget-togglebutton="false" data-widget-deletebutton="false"
						data-widget-fullscreenbutton="false"
						data-widget-custombutton="false" data-widget-sortable="false"
						style="height: 260px;">
						<header>
							<span class="widget-icon"> <i
								class="glyphicon glyphicon-stats txt-color-darken"></i></span>
							<h2>月资源使用监控</h2>
							<div class="col-sm-4 col-md-4 col-lg-2">
								<label class="select"> <select class="required"
									style="width: 150px" id="metricSelectMonth"
									name="metricSelectMonth">
										<option value="">选择监控项</option>
								</select>
								</label>
							</div>
						</header>
						<!-- widget div-->
						<!-- widget edit box -->
						<div class="jarviswidget-editbox"></div>
						<!-- end widget edit box -->
						<!-- content -->
						<div id="chartMonth" class="chart txt-color-blue"
							style="height: 260px;"></div>
						<!-- end widget div -->
					</div>
				</article>
			</div>
		</div>
		<!-- myTabContent1 end -->
	</div>
	<div class="modal fade" id="taskModal" tabindex="-1" role="dialog"
		aria-labelledby="taskModalLabel" aria-hidden="true">
		<div class="modal-dialog" style="width: 1200px;" id="dialogmodal">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">&times;</button>
					<h4 class="modal-title" id="taskModalLabel">任务状态提示</h4>
				</div>
				<div class="modal-body">
					<div class="table-responsive">
						<table class="table table-bordered">
							<thead>
								<tr>
									<th>所属者</th>
									<th>操作时间</th>
									<th>对象类型</th>
									<th>对象名称</th>
									<th>任务类型</th>
									<th>状态</th>
									<th>回执信息</th>
								</tr>
							</thead>
							<tbody id="mainframestate">
							</tbody>
						</table>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭
					</button>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal -->
	</div>
	<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<!-- content will be filled here -->
			</div>
		</div>
	</div>
</div>
<script>
    pageSetUp();
    loadScript("js/plugin/jqgrid/grid.locale-en.min.js", function(){
    	loadScript("js/plugin/jqgrid/jquery.jqGrid.min.js", function(){
    		sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId"),fillForm,ListAlert,null);
    	});
    });
    
    var metricSelectDay, $metricSelectDay;
    var metricSelectMonth, $metricSelectMonth;
    
    var chartDay = echarts.init(document.getElementById('chartDay'));
    var chartMonth = echarts.init(document.getElementById('chartMonth'));
    chartDay.resize({width: 1024});
    chartMonth.resize({width: 1024});
    
    var dayData = [],
		monthData = [],
		legendDayData = [],
		legendMonthData = [];
    var now = new Date(),
		hour = 1000 * 60 * 60,
		day = hour * 24,
		month = 30 * day,
		nowLimit = Math.round(now / day) * day + day,
		month = 31 * day;
    var yAxisDayGap = yAxisMonthGap = 0;
    var dayInterval = 0;
    var dayMonitorType = monthMonitorType = "";
    
    var monitorUnitId;
    
    function fillForm(data){
    	$("#siteName").append(data.data['siteName']);
        $("#areaName").append(data.data['areaName']);
        $("#owner").append(data.data['owner']);
        $("#businessSystemName").append(data.data['businessSystemName']);
        $("#businessSubSystemName").append(data.data['businessSubSystemName']);
        $("#servName").append(data.data['servName']);
        $("#statusText").append(data.data['statusText']);
        $("#createDateTime").append(data.data['createDateTime']);
        $("#taskStatusText").append(data.data['taskStatusText']);
        $metricSelectDay = $("#metricSelectDay").selectize({
    		valueField: 'id',
    		labelField: 'text',
    		searchField: 'text',
    		create: true,
    		sortField: {field: 'text'},
    		options: []
    	});
        metricSelectDay = $metricSelectDay[0].selectize;
        $("#metricSelectDay").change(function(){
        	dayInterval != 0 ? clearInterval(dayInterval) : dayInterval;
    		dayInterval = 0;
    		
    		dayData = [];
    		legendDayData = [];
    		yAxisDayGap = 0;
    		dayIndex = 0;
    		
    		chartDay.setOption({
    			legend: {
    	            data: legendDayData
    	        },
	        	series: dayData,
		        dataZoom: genDayDataZoom()
	    	});
    		chartDay.showLoading();
    		
    		dayMonitorType = $(this.selectedOptions).val();
    		
    		// e.date 内置date为UTC
    		var d = $('#timepicker').datepicker('getDate').getTime() + day == nowLimit - 8 * hour ?  new Date() : $('#timepicker').datepicker('getDate');
    		console.log($(this.selectedOptions).val());
        	sendGetWithoutLayer("/upm_manager/v1.0/monitor/unit/"+monitorUnitId+"/"+$(this.selectedOptions).val()+DateToDayParam(d),initDayChart,ListAlert,null);
    	});
        
        $metricSelectMonth = $("#metricSelectMonth").selectize({
    		valueField: 'id',
    		labelField: 'text',
    		searchField: 'text',
    		create: true,
    		sortField: {field: 'text'},
    		options: []
    	});
        metricSelectMonth = $metricSelectMonth[0].selectize;
        
        $("#metricSelectMonth").change(function(){
    		monthData = [];
    		legendMonthData = [];
    		yAxisMonthGap = 0;
    		monthIndex = 0;
    		
    		chartMonth.setOption({
    			legend: {
    	            data: legendMonthData
    	        },
	        	series: monthData,
		        dataZoom: genMonthDataZoom()
	    	});
    		chartMonth.showLoading();
    		
    		monthMonitorType = $(this.selectedOptions).val();
    		
    		// e.date 内置date为UTC
    		var d = new Date();
        	sendGetWithoutLayer("/upm_manager/v1.0/monitor/unit/"+monitorUnitId+"/"+$(this.selectedOptions).val()+DateToMonthParam(d),initMonthChart,ListAlert,null);
    	});
        
        $('#timepicker').datepicker({
        	language: 'zh-CN',
        	endDate: now,
        	startDate: new Date(nowLimit - month),
        	autoclose: true
        }).datepicker('setDate', DateToStrYYYYMMDD(now))
        	.on('changeDate', function(e) {
        		dayInterval != 0 ? clearInterval(dayInterval) : dayInterval;
        		dayInterval = 0;
        		
        		dayData = [];
        		legendDayData = [];
        		yAxisDayGap = 0;
        		dayIndex = 0;
        		
        		chartDay.setOption({
        			legend: {
        	            data: legendDayData
        	        },
    	        	series: dayData,
    		        dataZoom: genDayDataZoom()
    	    	});
        		chartDay.showLoading();
        		
        		// e.date 内置date为UTC
        		var d = e.date.getTime() + day == nowLimit - 8 * hour ?  new Date() : e.date;
        		
        		sendGetWithoutLayer("/upm_manager/v1.0/monitor/unit/"+monitorUnitId+"/"+metricSelectDay.getValue()+DateToDayParam(d),initDayChart,ListAlert,null);
        	})
        	.on('show', function(e) {
        		now = new Date();
        		if(nowLimit < now.getTime()){
        			nowLimit = Math.round(now / day) * day + day;
        			$('#timepicker').datepicker('setEndDate', now);
        			$('#timepicker').datepicker('setStartDate', new Date(nowLimit - month));
        		}
        	});
        
        chartDay.setOption({
            legend: {
                data: legendDayData
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                	var tooltip = '';
                	$.each(params, function(k, v){
                		var date = new Date(Number(v.name));
                		tooltip += v.seriesName + '  ' + date.getFullYear() +  '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' ' + (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':' + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + '  ' + v.value[1];
                		tooltip += "</br>";
                	});
                    
                    return tooltip;
                },
                axisPointer: {
                    animation: false
                }
            },
            xAxis: {
                type: 'time'
            },
            yAxis: {
                type: 'value',
                boundaryGap: [0, '100%'],
                min: 0,
                max: 100,
                axisLabel: {
	        		formatter: yAxisFormatter
	        	}
            },
            dataZoom: genDayDataZoom(),
            legend: {
                data: legendDayData
            },
            series: dayData
        });
        
        chartMonth.setOption({
            legend: {
                data: legendMonthData
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                	var tooltip = '';
                	$.each(params, function(k, v){
                		var date = new Date(Number(v.name));
                		tooltip += v.seriesName + '  ' + date.getFullYear() +  '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' ' + (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':' + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + '  ' + v.value[1];
                		tooltip += "</br>";
                	});
                    
                    return tooltip;
                },
                axisPointer: {
                    animation: false
                }
            },
            xAxis: {
                type: 'time'
            },
            yAxis: {
                type: 'value',
                boundaryGap: [0, '100%'],
                min: 0,
                max: 100,
                axisLabel: {
	        		formatter: yAxisFormatter
	        	}
            },
            dataZoom: genMonthDataZoom(),
            legend: {
                data: legendMonthData
            },
            series: monthData
        });
        
        sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/subservs/upsql',createGrid_mysql_m1,ListAlert,null);
        sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/subservs/upsql/configs',createGrid_mysql_m2,ListAlert,null);
        sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/backup_strategys',createGrid_mysql_m3,ListAlert,null);
        sendGet("/upm_manager/v1.0/backupfiles?serv="+getSession("serviceUpsqlId")+'&site='+getSession("siteId"),createGrid_mysql_m4,ListAlert,null);
        
        createGrid_mysql_m5(relationDataGen(data));
        
        //sendGet(getPost()+"/v1.0/servs/"+getSession("serviceUpsqlId")+'/users',createGrid_mysql_m6,ListAlert,null);
        sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/databases',createGrid_mysql_m7,ListAlert,null);
    }
    
    function relationDataGen(data){
    	var relationData = [];
        $.each(data.data.subServs, function(indexSubServ, subServ){
        	$.each(subServ.units, function(indexUnit, unit){
        		if(unit.type == "upsql"){
        			relationData.push({
            			relateName: unit.relateName,
            			serverIp: unit.serverIp,
            			portValue: unit.portValue,
            			hostIp: unit.hostIp,
            			hostName: unit.hostName,
            			statusText: unit.statusText,
            			containerStatus: unit.containerStatus,
            			role: unit.role
            		});
        		}
        	});
        });
        return relationData;
    }
    
    $('#taskModal').on("show.bs.modal", function(e){
    	ListAlertClear();
    	$("#mainframestate").empty();
    	sendGet("/upm_manager/v1.0/tasks?obj_id="+$(e.relatedTarget).data('upsql-id'),createGrid_serviceDetail,ListAlert,null);
    });
    
    function upsqlTabClick(){
    	$("#jqgrid").jqGrid('GridUnload');
    	$("#restoreBtn").show();
    	$("#backupBtnBtn").show();
    	$("#rebuildBtn").show();
    	$("#isolateBtn").show();
    	$("#recoverBtn").show();
    	$("#slowlog").show();
    	sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/subservs/upsql',createGrid_mysql_m1,ListAlert,null);
    }
    
    function upproxyTabClick(){
    	$("#jqgrid").jqGrid('GridUnload'); 
    	$("#restoreBtn").hide();
    	$("#backupBtnBtn").hide();
    	$("#rebuildBtn").hide();
    	$("#isolateBtn").hide();
    	$("#recoverBtn").hide();
    	$("#slowlog").hide();
    	sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/subservs/upproxy',createGrid_upproxy,ListAlert,null);
    }
    
    function swmTabClick(){
    	$("#jqgrid").jqGrid('GridUnload');
    	$("#restoreBtn").hide();
    	$("#backupBtnBtn").hide();
    	$("#rebuildBtn").hide();
    	$("#isolateBtn").hide();
    	$("#recoverBtn").hide();
    	$("#slowlog").hide();
    	sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/subservs/switch_manager',createGrid_switch_manager,ListAlert,null);
    }
    
    function relationMonitorTabClick(){
    	sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId"),reloadRelationMonitorGrid,ListAlert,null);
    }
    
    function userTabClick(){
    	ListAlertClear();
    	sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/users',create_User_Grid,ListAlert,null);
    }
    
    function userDirectTabClick(){
    	ListAlertClear();
    	sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/direct_users',create_User_Grid,ListAlert,null);
    }
    
    function databaseTabClick(){
    	sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/databases',reloadDatabaseGrid,ListAlert,null);
    }
    
    function backupListTabClick(){
    	sendGet("/upm_manager/v1.0/backupfiles?serv="+getSession("serviceUpsqlId")+'&site='+getSession("siteId"),reloadBackupListGrid,ListAlert,null);
    }
    
    function backupStrategyTabClick(){
    	sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/backup_strategys',reloadBackupStrategyGrid,ListAlert,null);
    }
    
    function reloadRelationMonitorGrid(data){
    	ListAlertClear();  	
    	$("#jqgrid").clearGridData().setGridParam({data:relationDataGen(data)}).trigger("reloadGrid");
    }
    
    function reloadUnitGrid(data){
    	ListAlertClear();
    	var colornum = '';
    	var dataArray=new Array();
    	for(var i=0;i<data['data'].length;i++){
    		(i%2 ==0) ?colornum = "333333":colornum = "900323";
    		for(var k=0;k<data['data'][i]['units'].length;k++){
    			data['data'][i]['units'][k]['fontcolor'] = colornum;
    			dataArray.push(data['data'][i]['units'][k]);
    		}
    	}
    	var jq_data=dataArray;
    	$("#jqgrid").clearGridData().setGridParam({data:jq_data}).trigger("reloadGrid");
    }
    
    function reloadDatabaseGrid(data){
    	ListAlertClear();
    	var jq_data=data['data'];   	
    	$("#jqgridDatabase").clearGridData().setGridParam({data:jq_data}).trigger("reloadGrid");
    }
    
    function reloadBackupListGrid(data){
    	ListAlertClear(); 
    	var jq_data=data['data']; 
    	$("#jqgridBackupList").clearGridData().setGridParam({data:jq_data}).trigger("reloadGrid");
    }
    
    function reloadBackupStrategyGrid(data){
    	ListAlertClear();  	
    	$("#jqgridBackupStrategy").clearGridData().setGridParam({data:relationDataGen(data)}).trigger("reloadGrid");
    }
    
    function unit(type){
    	ListAlertClear();
    	var s = $("#jqgrid").jqGrid('getGridParam', 'selarrrow');
    	var id = $("#restoreBtn");
    	if(s.length == 1){
    		 var unitId = $("#jqgrid").jqGrid('getRowData',s).id;
    		 switch(type){
    		 case "start":
    			 sendPut("/upm_manager/v1.0/units/"+unitId+"/start",unitShowReturn,ListAlert,null,null);
    			 break;
    		 case "stop":
    			 sendPut("/upm_manager/v1.0/units/"+unitId+"/stop",unitShowReturn,ListAlert,null,null);
    			 break;
    		 case "backup":
    			 sendPut("/upm_manager/v1.0/units/"+unitId+"/backup",unitShowReturn,ListAlert,null,null);
    			 break;
    		 case "restore":
    			 ListAlertClear();
    			 var myhref=getManagerViews()+'service/upsql/restore.html';
		            id.attr("href",myhref);
		            id.attr("data-toggle","modal");
		            id.attr("data-target","#myModal");
    			 break;
    		 case "migrate":
    			 sendPut("/upm_manager/v1.0/units/"+unitId+"/migrate",unitShowReturn,ListAlert,null,null);
    			 break;
    		 case "rebuild":
    			 sendPut("/upm_manager/v1.0/units/"+unitId+"/rebuild",unitShowReturn,ListAlert,null,null);
    			 break;
    		 case "monitor":
    			 monitorUnitId = unitId;
    			 monitorTabToggle($("#myTab1").find("li.active").eq(0).find("a").attr("id"));
    			 $('#monitorTab').tab('show');
    			 break;
    		 case "isolate":
    			 sendPut("/upm_manager/v1.0/units/"+unitId+"/isolate",unitShowReturn,ListAlert,null,null);
    			 break;
    		 case "recover":
    			 sendPut("/upm_manager/v1.0/units/"+unitId+"/recover",unitShowReturn,ListAlert,null,null);
    			 break;
    		 case "slowlog":
    			 ListAlertClear();
    			 var logid = $("#slowlog");
	    			 logid.attr("href","views/service/upsql/slowlog.html");
	    			 logid.attr("data-toggle","modal");
	    			 logid.attr("data-target","#slowlogModal");
	    			 sendGet("/upm_manager/v1.0/units/"+unitId+"/slowlog",createGrid_slowlog,null);
    			 break;
    		 default:
    		 }
    	 } else{
    		 ListAlert("请勾选一行数据");
             id.removeAttr("data-toggle");
             id.removeAttr("data-target");
             id.removeAttr("href");
    	 }
    }
    
    function paramTabClick(type){
    	switch(type){
    	case "upsql":
    		sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+"/subservs/upsql/configs",reloadParamGrid,ListAlert,null);
			 break;
		 case "upproxy":
			 sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+"/subservs/upproxy/configs",reloadParamGrid,ListAlert,null);
			 break;
		 default:
    	}
    }
    
    function userClick(type){
    	switch(type){
    	case "add":
    		var id = $("#addUser");
            id.attr("href","views/service/upsql/addUser.html");
            id.attr("data-toggle","modal");
            id.attr("data-target","#myModal");
			break;
    	case "delete":
    		var s = $("#jqgridUser").jqGrid('getGridParam', 'selarrrow');
    		if(s.length == 1){
	    		var userName = $("#jqgridUser").jqGrid('getRowData',s).username;
	    		sendDelete(getAPI()+"servs/"+getSession("serviceUpsqlId")+"/users/"+userName, userShowReturn, ListAlert, null ,null);
    		}else{
				 ListAlert("请勾选一行数据");
	             id.removeAttr("data-toggle"); 
	             id.removeAttr("data-target");
	             id.removeAttr("href");
			}
	    	break;
    	case "addDirect":
    		var id = $("#addUserDirect");
            id.attr("href","views/service/upsql/addUserDirect.html");
            id.attr("data-toggle","modal");
            id.attr("data-target","#myModal");
			break;
    	case "deleteDirect":
    		var s = $("#jqgridUser").jqGrid('getGridParam', 'selarrrow');
    		if(s.length == 1){
	    		var userName = $("#jqgridUser").jqGrid('getRowData',s).username;
	    		sendDelete("upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+"/direct_users/"+userName, userShowReturn, ListAlert, null ,null);
    		}else{
				 ListAlert("请勾选一行数据");
	             id.removeAttr("data-toggle"); 
	             id.removeAttr("data-target");
	             id.removeAttr("href");
			}
	    	break;
		 default:
    	}
    }
    
    function backupStrategyClick(type){
    	var s = $("#jqgridBackupStrategy").jqGrid('getGridParam', 'selarrrow');
    	var backup_strategy_id = $("#jqgridBackupStrategy").jqGrid('getRowData',s).id;
    	switch(type){
    	case "delete":
			if(s.length == 1){
				sendDelete("upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+"/backup_strategys/"+backup_strategy_id, backupStrategyTabClick, ListAlert, null);
			}else{
				 ListAlert("请勾选一行数据");
	             id.removeAttr("data-toggle");
	             id.removeAttr("data-target");
	             id.removeAttr("href");
			}
			break;
		 case "start":
			if(s.length == 1){
				sendPut("upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+"/backup_strategys/"+backup_strategy_id+"/enable",backupStrategyTabClick,ListAlert,null,null);
			}else{
				 ListAlert("请勾选一行数据");
	             id.removeAttr("data-toggle");
	             id.removeAttr("data-target");
	             id.removeAttr("href");
			}
		    break;
		 case "stop":
			if(s.length == 1){
				sendPut("upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+"/backup_strategys/"+backup_strategy_id+"/disable",backupStrategyTabClick,ListAlert,null,null);
			}else{
				ListAlert("请勾选一行数据");
		        id.removeAttr("data-toggle");
		        id.removeAttr("data-target");
		        id.removeAttr("href");
			}
			break;
		 case "edit":
			 var id = $("#editBackupStrategy");
			 if(s.length == 1){
			     id.attr("href","views/service/upsql/editBackupStrategy.html");
			     id.attr("data-toggle","modal");
			     id.attr("data-target","#s4remoteModal");
			 }else{
				 ListAlert("请勾选一行数据");
			     id.removeAttr("data-toggle");
			     id.removeAttr("data-target");
			     id.removeAttr("href");
			 }
			break;
		 default:
    	}
    }
    
    function databaseClick(type){
    	switch(type){
    	case "add":
    		var id = $("#addDatabase");
            id.attr("href","views/service/upsql/addDatabase.html");
            id.attr("data-toggle","modal");
            id.attr("data-target","#s7remoteModal");
			break;
		 case "delete":
			var s = $("#jqgridDatabase").jqGrid('getGridParam', 'selarrrow');
			if(s.length == 1){
				var databaseName = $("#jqgridDatabase").jqGrid('getRowData',s).name;
				sendDelete("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+"/databases/"+databaseName, databaseShowReturn, ListAlert, null);
			}else{
				 ListAlert("请勾选一行数据");
	             id.removeAttr("data-toggle");
	             id.removeAttr("data-target");
	             id.removeAttr("href");
			}
		    break;
		 default:
    	}
    }
    
    function databaseShowReturn(){
    	sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/databases',reloadDatabaseGrid,ListAlert,null);
    }
    
    function userShowReturn(){
    	sendGet("/upm_manager/v1.0/servs/"+getSession("serviceUpsqlId")+'/users',reloadUserGrid,ListAlert,null);
    }
    
	function reloadUserGrid(data){
		ListAlertClear();
    	var jq_data=data['data'];   	
    	$("#jqgridUser").clearGridData().setGridParam({data:jq_data}).trigger("reloadGrid");
    }
    
    function reloadParamGrid(data){
    	ListAlertClear();
    	var jq_data=data['data'];   	
    	$("#jqgridParam").clearGridData().setGridParam({data:jq_data}).trigger("reloadGrid");
    }
    
    function reloadBackupStrategyGrid(data){
    	ListAlertClear();
    	var jq_data=data['data'];   	
    	$("#jqgridBackupStrategy").clearGridData().setGridParam({data:jq_data}).trigger("reloadGrid");
    }
    
    function unitShowReturn(){
		 switch($("#myTab1").find("li.active").eq(0).find("a").attr("id")){
		 case "upsqlTab":
			 upsqlTabClick();
			 break;
		 case "upproxyTab":
			 upproxyTabClick();
			 break;
		 case "swmTab":
			 swmTabClick();
			 break;
		 default:
		 }
	}
    
    function editParam(){
    	ListAlertClear();
        s = $("#jqgridParam").jqGrid('getGridParam', 'selarrrow');
        var rowData = $("#jqgrid").jqGrid('getRowData',s);
        var id=$("#updateParam");
        if(s.length==1){
            id.attr("href","views/service/upsql/param.html");
            id.attr("data-toggle","modal");
            id.attr("data-target","#myModal");
        } else {
        	ListAlert("请勾选一行数据");
            id.removeAttr("data-toggle");
            id.removeAttr("data-target");
            id.removeAttr("href");
        }
    }
    
    function addBackupStrategyClick(){
        var id=$("#addBackupStrategy");
        id.attr("href","views/service/upsql/addBackupStrategy.html");
        id.attr("data-toggle","modal");
        id.attr("data-target","#s4remoteModal");
    }
    
    function monitorTabToggle(tabType){
    	dayInterval != 0 ? clearInterval(dayInterval) : dayInterval;
		dayInterval = 0;
		
    	metricSelectDay.clearOptions();
    	metricSelectMonth.clearOptions();
    	switch(tabType){
    	case 'upsqlTab':
    		metricSelectDay.addOption({id:"all_cpu_usage", text:"cpu"});
    		metricSelectDay.addOption({id:"mem_usage", text:"内存"});
    		metricSelectDay.addOption({id:"sql_press", text:"负载"});
    		metricSelectDay.setValue(['all_cpu_usage']);
    		
    		metricSelectMonth.addOption({id:"all_cpu_usage", text:"cpu"});
    		metricSelectMonth.addOption({id:"mem_usage", text:"内存"});
    		metricSelectMonth.addOption({id:"sql_press", text:"负载"});
    		metricSelectMonth.setValue(['all_cpu_usage']);
    		break;
    	case 'upproxyTab':
    		break;
    	default:
    	}
    }
    
    function initDayChart(data){
    	switch(metricSelectDay.getValue()){
		case "all_cpu_usage":
		case "mem_usage":
			var d = [];
    		legendDayData.push(metricSelectDay.getValue());
    		$.each(data.data, function(i, v){
    			d.push({
        			name: v.timestamp.toString(),
                    value: [
                    	v.timestamp,
                    	Math.round(v.value * 100) / 100
                    ]
        		});
        		yAxisDayGap < (Math.round(v.value * 100) / 100) ? (yAxisDayGap = Math.round(v.value * 100) / 100) : yAxisDayGap;
    		});
    		dayData.push({
                name: metricSelectDay.getValue(),
                type: 'line',
                data: d
            });
    		break;
		case "sql_press":
			$.each(data.data, function(key, value){
				var d = [];
	    		legendDayData.push(key);
	    		$.each(value, function(i, v){
	    			d.push({
	        			name: v.timestamp.toString(),
	                    value: [
	                    	v.timestamp,
	                    	Math.round(v.value * 100) / 100
	                    ]
	        		});
	        		yAxisDayGap < (Math.round(v.value * 100) / 100) ? (yAxisDayGap = Math.round(v.value * 100) / 100) : yAxisDayGap;
	    		});
	    		dayData.push({
	                name: key,
	                type: 'line',
	                data: d
	            });
			});
			break;
		default:
		}
    	
    	chartDay.setOption({
    		legend: {
	            data: legendDayData
	        },
	        series: dayData,
	        dataZoom: genDayDataZoom()
	    });
    	chartDay.hideLoading();
    	
		if (Math.round($('#timepicker').datepicker('getDate').getTime() / day) * day + day == nowLimit && data.data.length != 0) {
			dayInterval = setInterval(function () {
				sendGetWithoutLayer("/upm_manager/v1.0/monitor/unit/"+monitorUnitId+"/all_cpu_usage",function(data){
	    			dayData[0].data.shift();
	    			dayData[0].data.push({
	    	    		name: data.data.timestamp.toString(),
	                    value: [
	                    	data.data.timestamp,
	                    	Math.round(data.data.value * 100) / 100
	                    ]
	    	    	});
	    	    	chartDay.setOption({
	        	        series: dayData
	        	    });
	    		},ListAlert,null);
	    	}, 60 * 1000);
		}
    }
    
    function initMonthChart(data){
    	switch(metricSelectMonth.getValue()){
		case "all_cpu_usage":
		case "mem_usage":
			var d = [];
    		legendMonthData.push(metricSelectMonth.getValue());
    		$.each(data.data, function(i, v){
    			d.push({
        			name: v.timestamp.toString(),
                    value: [
                    	v.timestamp,
                    	Math.round(v.value * 100) / 100
                    ]
        		});
        		yAxisMonthGap < (Math.round(v.value * 100) / 100) ? (yAxisMonthGap = Math.round(v.value * 100) / 100) : yAxisMonthGap;
    		});
    		monthData.push({
                name: metricSelectMonth.getValue(),
                type: 'line',
                data: d
            });
    		break;
		case "sql_press":
			$.each(data.data, function(key, value){
				var d = [];
	    		legendMonthData.push(key);
	    		$.each(value, function(i, v){
	    			d.push({
	        			name: v.timestamp.toString(),
	                    value: [
	                    	v.timestamp,
	                    	Math.round(v.value * 100) / 100
	                    ]
	        		});
	        		yAxisMonthGap < (Math.round(v.value * 100) / 100) ? (yAxisMonthGap = Math.round(v.value * 100) / 100) : yAxisMonthGap;
	    		});
	    		monthData.push({
	                name: key,
	                type: 'line',
	                data: d
	            });
			});
			break;
		default:
		}
    	
    	chartMonth.setOption({
    		legend: {
	            data: legendMonthData
	        },
	        series: monthData,
	        dataZoom: genMonthDataZoom()
	    });
    	chartMonth.hideLoading();
    }
    
    function genDayDataZoom(){
    	return [
            {
                type: 'slider',
                show: true,
                xAxisIndex: [0]
            },
            {
                type: 'slider',
                show: true,
                yAxisIndex: [0],
                end: (yAxisDayGap + 10 < 100) ? yAxisDayGap + 10 : 100
            },
            {
                type: 'inside',
                xAxisIndex: [0]
            },
            {
                type: 'inside',
                yAxisIndex: [0],
                end: (yAxisDayGap + 10 < 100) ? yAxisDayGap + 10 : 100
            }
        ];
    }
    
    function genMonthDataZoom(){
    	return [
            {
                type: 'slider',
                show: true,
                xAxisIndex: [0]
            },
            {
                type: 'slider',
                show: true,
                yAxisIndex: [0],
                end: (yAxisMonthGap + 10 < 100) ? yAxisMonthGap + 10 : 100
            },
            {
                type: 'inside',
                xAxisIndex: [0]
            },
            {
                type: 'inside',
                yAxisIndex: [0],
                end: (yAxisMonthGap + 10 < 100) ? yAxisMonthGap + 10 : 100
            }
        ];
    }
    
    function yAxisFormatter(value, index){
		switch(metricSelectDay.getValue()){
		case "all_cpu_usage":
		case "mem_usage":
			return value + '%';
		default:
			return value;
		}
	}
    
    function crontabToLabel(crontab){
    	var crons = crontab.split(' ');
    	var ret = "";
    	if(crons[2] == "*" && crons[3] == "*" && crons[4] == "*"){
    		ret += '每天 ';
    	} else {
    		return 'TODO';
    	}
    	ret += crons[1]+':'+crons[0];
    	return ret;
    }
    
</script>